﻿/*!
 * redsand common javascript
 * version 2.5
 */

$(function () {
    autoZen();
});

function ajax_failure(data) {
    alert(data.responseText);
    showMessage('System error');
}
function ajax_get_list_success(data) {
    if (!isJavascriptResult(data)) {
        closeDialog('.ui-dialog .dialog');
        generateForList();
        generateForAll(); 
        getAjaxMessage();
    }
}
function ajax_change_password_success(data) {
    if (!isJavascriptResult(data)) {
        closeDialog('.change-password');
    }
}
function ajax_get_form_success(data) {
    if (!isJavascriptResult(data)) {
        closeDialog('.ui-dialog .dialog');
        $('.dialog').dialog({
            modal: true,
            padding: '0',
            close: function () {
                closeDialog(this);
            },
            resizable: false,
            minWidth: $('.dialog').width(),
            minHeight: $('.dialog').height()
        });
        generateForForm();
        generateForAll(); 
        getAjaxMessage();
        setTimeout(editorAddControl, 100);
        createAvatarUpload('#choose-avatar');
        setTimeout(fixHeight, 1000);
        setTimeout(fixHeight, 2000);
    }
}

function getAjaxMessage() {
    $.get("/base/getmessage", function (data) {
        showMessage(data);
    });
}
function showMessage(message) {
    message = message.toString();
    if ($.trim(message) != "") {
        $('#loading-panel').css('display', 'none');
        if (message.indexOf('[msg]') == 0) {
            message = message.substring(5);
        }
        var s = message.split('[msg]');
        for (i in s) {
            alert(s[i]);
        }
    }
}
function isJavascriptResult(data) {
    if (data == null) return false;
    return (data.indexOf('showMessage') == 0 || data.indexOf('alert') == 0 || data.indexOf('location') == 0);
}

function closeDialog(dialog) {
    editorRemoveControl(dialog);
    $(dialog).remove();
    $('#wrapper').height('auto');
}

function fixHeight() {
    if ($('#wrapper').outerHeight(true) < $(document).height()) {
        $('.ui-widget-overlay').height($('#wrapper').outerHeight(true));
        $('#wrapper').height($(document).height());
        $('.ui-widget-overlay').height($('#wrapper').outerHeight(true));
    }
}
function getResourceString(tag, group) {
    var obj = jQuery.data(document.body, group);
    if (obj) return eval("obj." + tag);
    return "";
}
//box
function generateForList() {
    $('.rs-pager a:eq(1)').css('border-radius', '15px 0 0 15px');
    $('.rs-pager a:last').css('border-radius', '0 15px 15px 0');

    $('.btn-search').unbind('click');
    $('.btn-search').click(function () {
        var search = $(this).parents('.panel').find('.panel-searchbox');
        $.cookie('panel-searchbox-display', search.css('display') == 'block' ? 'none' : 'block');
        search.slideToggle(400);
        return false;
    });

    $('.panel-searchbox').css('display', $.cookie('panel-searchbox-display'));

    $('.choose-file').hover(function () {
        $(this).css('border-color', '#aaaaaa');
    }, function () {
        $(this).css('border-color', '#c5c5c5');
    });

    $('.pager-wrapper').has('.rs-pager').css('display', 'block');

    //table
    $('.table-list th:first input:checkbox').change(function () {
        $('.table-list tr').find('td:first input:checkbox').attr('checked', this.checked);
    });
    $('.table-list tr').find('td:first input:checkbox').change(function () {
        var size1 = $('.table-list tr').find('td:first input:checked').size();
        var size2 = $('.table-list tr').find('td:first input:checkbox').size();
        $('.table-list th:first input:checkbox').attr('checked', size1 == size2);
    });

    $('.btn-deletes').unbind('click');
    $('.btn-deletes').click(function () {
        var inp = $(this).parents('.panel').find('.table-list tr').find('td:first input:checked');
        if (inp.size() == 0) {
            showMessage({ tag: 'NoRecordsAreSelected' });
            return false;
        }
        var ids = '';
        var href = $(this).attr('href');

        inp.each(function () {
            ids += 'id=' + $(this).val() + '&';
        });

        if (href.indexOf('id=') > 0) {
            href = href.replace(/(id=\d+&?)+/g, ids);
        }
        else if (href.indexOf('?') > 0) {
            href += '&' + ids;
        }
        else {
            href += '?' + ids;
        }
        href = href.replace(/&$/, '');
        $(this).attr('href', href);
    });
}
function generateForForm() {
    $('.form-cell').find('input:text, input:password, textarea, input:file').width(function () {
        if (($(this).attr('style') || '').indexOf('width') < 0) {
            var delta = $(this).outerWidth(true) - $(this).width();
            return $(this).parent().width() - delta;
        }
    });
}
function generateForAll() {
    // for theme
    theme_init();

    $('.date-picker').datepicker({
        dateFormat: (getResourceString('ShortDate', 'StringFormat').toLowerCase().replace(/yy/g, 'y') || 'mm/dd/yy').replace('[Empty]', ''),
        changeMonth: true,
        changeYear: true
    });
    $('[class*=width]').width(function () {
        var cssClass = $(this).attr('class').toLowerCase();
        var cssClass = cssClass.substring(cssClass.lastIndexOf('width'));
        if (cssClass.indexOf(' ') > 0) cssClass = cssClass.substring(0, cssClass.indexOf(' '));
        return cssClass.replace('width-', '').replace('width', '');
    });
    $('[class*=height]').height(function () {
        var cssClass = $(this).attr('class').toLowerCase();
        var cssClass = cssClass.substring(cssClass.lastIndexOf('height'));
        if (cssClass.indexOf(' ') > 0) cssClass = cssClass.substring(0, cssClass.indexOf(' '));
        return cssClass.replace('height-', '').replace('height', '');
    });
}
function autoZen() {
    generateForList();
    generateForForm();
    generateForAll();    
}

// upload avatar

function createAvatarUpload(elements) {

    var preview = "#upload-image-preview";

    $(elements).rsAjaxUpload({
        beforeSubmit: function (arr, form) {
            var filename = $.trim(form.find('input').val());
            var filefilter = ".jpg|.png|.bmp|.gif|.jpeg";
            var ext = filename.substring(filename.lastIndexOf('.')).toLowerCase();
            if (filefilter.indexOf(ext) < 0) {
                showMessage('File format wrong');
                return false;
            }
            $(elements).addClass('loading');
        },
        success: function (data) {
            $(elements).removeClass('loading');
            if (data.indexOf('Error:') < 0) {
                data = data.replace('&amp;', '&');
                $(preview).attr('src', data);
                $(elements).val(data);
            }
            else {
                showMessage(data.replace('Error:', ''));
            }
        },
        error: function (data) {
            $(elements).removeClass('loading');
            showMessage('File size too large');
            $(preview).attr('src', '');
        }
    });
}

//tiny editor

function editorAddControl() {
    $('.dialog').find('.editor').each(function () {
        var st = $(this).attr('settings');
        if (st == null || st == 'undefined') st = {};
        tinyMCE.settings = $.extend({}, tiny_editor_settings, eval(st));
        tinyMCE.execCommand('mceAddControl', false, $(this).attr('id'));
    });
}
function editorRemoveControl(dialog) {
    $(dialog).find('.editor').each(function () {
        tinyMCE.execCommand('mceRemoveControl', false, $(this).attr('id'));
    });
}
var tiny_editor_settings = {
    mode: "none",
    encoding: "xml",
    theme: "advanced",
    skin: "o2k7",
    skin_variant: "silver",
    width: '100%',
    height: '500px',
    relative_urls: false,
    entity_encoding: "raw",

    save_callback: function (element_id, html, body) {
        html = html.replace(/&#39;/g, "'");
        return html;
    },

    plugins: "autolink,lists,style,layer,table,advimage,advlink,emotions,iespell,preview,media,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,inlinepopups,netImageBrowser",

    // Theme options
    theme_advanced_buttons1: "bold,italic,underline,strikethrough,|,forecolor,backcolor,|,justifyleft,justifycenter,justifyright,justifyfull,formatselect,fontselect,fontsizeselect,|,bullist,numlist,|,outdent,indent,blockquote,charmap",
    theme_advanced_buttons2: "cut,copy,paste,pastetext,pasteword,|,link,unlink,anchor,image,netImageBrowser,media,|,code,|,insertlayer,|,tablecontrols,|,preview,fullscreen",
    theme_advanced_buttons3: "",
    theme_advanced_toolbar_location: "top",
    theme_advanced_toolbar_align: "left",
    theme_advanced_statusbar_location: ""
};